package org.flint92.springboot.security.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;

/**
 * @author flint92
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // csrf
        http.csrf().csrfTokenRepository(new CookieCsrfTokenRepository())
                .requireCsrfProtectionMatcher(
                        request -> request.getMethod().equals("POST") && request.getRequestURI().startsWith("/login")
                )
        ;

        // csp header
        http.headers().contentSecurityPolicy("script-src https://code.jquery.com/");

        // X-Frame-Options headers
        // same origin pass
        http.headers().frameOptions().sameOrigin();

        // white list
        http.headers().addHeaderWriter(new XFrameOptionsHeaderWriter(request -> "flint92.org"));

        // xss header
        http.headers().xssProtection().block(true);

        http.authorizeRequests().anyRequest().fullyAuthenticated()
                .and()
                    .formLogin()
                    .usernameParameter("name")
                    .passwordParameter("pwd")
                    .loginProcessingUrl("/loginAction")
                    .loginPage("/login")
                    .failureForwardUrl("/error")
                    .permitAll()
                .and()
                    .logout().permitAll();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("ADMIN")
                .and()
                .withUser("flint").password(new BCryptPasswordEncoder().encode("123456")).roles("USER");
    }
}
